package com.shenda.api.dao;

import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.shenda.api.entity.Data;
import com.swak.entity.Page;
import com.swak.entity.Parameters;
import com.swak.persistence.BaseJdbcDao;
import com.swak.persistence.QueryCondition;
import com.swak.utils.Maps;

/**
 * 数据库存储操作
 * 
 * @author lifeng
 */
@Repository
public class DatasDao extends BaseJdbcDao {

	/**
	 * 通过ID获取
	 * 
	 * @param id
	 * @return
	 */
	public Data get(String id) {
		Map<String, Object> param = Maps.newHashMap();
		param.put("id", id);
		return this.get(
				"SELECT ID, NAME, GYRO, STARTTIME, ENDTIME, CJMS, CJPL, ODR, TOTAL, TIMES, FRAMES FROM DATAS WHERE ID = :id",
				param, this.getRowMapper());
	}

	/**
	 * 插入
	 * 
	 * @param id
	 * @return
	 */
	public void delete(Data gyro) {
		gyro.prePersist();
		Map<String, Object> param = this.BeantoMap(gyro);
		this.delete("DELETE FROM DATAS WHERE ID =:id", param);
	}

	/**
	 * 插入
	 * 
	 * @param id
	 * @return
	 */
	public void insert(Data gyro) {
		gyro.prePersist();
		Map<String, Object> param = this.BeantoMap(gyro);
		this.insert(
				"REPLACE INTO DATAS(ID, NAME, GYRO, STARTTIME, ENDTIME, CJMS, CJPL, ODR, TOTAL, FRAMES, TIMES) VALUES(:id, :name, :gyro, :startTime, :endTime, :cjms, :cjpl, :odr, :total, :frames, :times)",
				param);
	}

	/**
	 * 修改 -- 暂时没用到
	 * 
	 * @param id
	 * @return
	 */
	public void updateFrames(Data gyro) {
		Map<String, Object> param = this.BeantoMap(gyro);
		this.insert("UPDATE DATAS SET FRAMES = :frames WHERE ID = :id", param);
	}

	/**
	 * 分页查询
	 * 
	 * @param gyro
	 * @param param
	 * @return
	 */
	public Page page(QueryCondition query, Parameters param) {
		String sql = "SELECT ID, NAME, GYRO, STARTTIME, ENDTIME, CJMS, CJPL, ODR, TOTAL, TIMES, FRAMES FROM DATAS";
		return this.page(sql, query, param, this.getRowMapper());
	}

	/**
	 * 数据转换
	 * 
	 * @return
	 */
	private RowMapper<Data> getRowMapper() {
		return (rs, num) -> {
			Data gyro = new Data();
			gyro.setId(rs.getString("ID"));
			gyro.setName(rs.getString("NAME"));
			gyro.setGyro(rs.getString("GYRO"));
			gyro.setStartTime(rs.getString("STARTTIME"));
			gyro.setEndTime(rs.getString("ENDTIME"));
			gyro.setCjms(rs.getString("CJMS"));
			gyro.setCjpl(rs.getString("CJPL"));
			gyro.setOdr(rs.getString("ODR"));
			gyro.setTotal(rs.getInt("TOTAL"));
			gyro.setTimes(rs.getLong("TIMES"));
			gyro.setFrames(rs.getInt("FRAMES"));
			gyro.setGyroName(gyro.crc16(gyro.getGyro(), true));
			return gyro;
		};
	}
}
